const koa = require("koa")
const path = require("path")
const static = require("koa-static")
const koaBody = require("koa-body")
const router = require("koa-router")()
const spanman = require("../../index")
const app = new koa()

// 先创建存放文件所需的文件夹
spanman.make_path(path.resolve(__dirname, "public/uploads"))

// 分多个文件可以将业务按需分离
const cors = require("koa2-cors")
const uploadFun = require("./upload")
const uploadFun2 = require("./upload2")
const downloadFun = require("./download")

app.use(koaBody({
    multipart: true,
    formidable: {
        uploadDir: path.resolve(__dirname, "public/uploads"),
        keepExtensions: true, // 保留文件的扩展名
        maxFieldsSize: 200 * 1024 * 1024 // 文件最大限制 默认是2m
    }
}))

// app.use(cors({
//     origin: function (ctx) {
//         if (ctx.url === "/test") {
//             return "*" // 返回什么即允许对应的域名
//         }
//         return "*"
//         // return "http://localhost:8000"
//     },
//     exposeHeaders: ["www-Authenticate", "Server-Authorization"],
//     maxAge: 5,
//     credentials: true,
//     allowMethods: ["GET", "POST", "DELETE"],
//     allowHeaders: ["Content-type", "Authorization", "Accept"]
// }))

app.use(cors())
    .use(uploadFun.routes())
    .use(uploadFun.allowedMethods())
    .use(uploadFun2.routes())
    .use(uploadFun2.allowedMethods())
    .use(downloadFun.routes())
    .use(downloadFun.allowedMethods())

// 优先级低于后面 app.use(router.routes()) 中的路由
router.get("/", async (ctx, next) => {
    ctx.response.body = "get / is ok"
})

app.use(router.routes())
app.use(static(path.resolve(__dirname, "public/uploads")))

app.listen(3001, console.log("koa is listen 3001"))
